package com.sugar.queryinfo.module.business.service.userbalancerecord;

import com.sugar.queryinfo.module.business.controller.admin.userextend.vo.UserExtendSaveReqVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import com.sugar.queryinfo.module.business.controller.admin.userbalancerecord.vo.*;
import com.sugar.queryinfo.module.business.dal.dataobject.userbalancerecord.UserBalanceRecordDO;
import com.sugar.queryinfo.framework.common.pojo.PageResult;
import com.sugar.queryinfo.framework.common.util.object.BeanUtils;

import com.sugar.queryinfo.module.business.dal.mysql.userbalancerecord.UserBalanceRecordMapper;

import static com.sugar.queryinfo.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.queryinfo.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.queryinfo.module.business.enums.ErrorCodeConstants.USER_BALANCE_RECORD_NOT_EXISTS;

/**
 * 余额变动记录 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class UserBalanceRecordServiceImpl implements UserBalanceRecordService {

    @Resource
    private UserBalanceRecordMapper userBalanceRecordMapper;

    @Override
    public void insertBalanceRecord(UserExtendSaveReqVO reqVO, BigDecimal preBalance, BigDecimal postBalance) {
        UserBalanceRecordDO balanceRecordDO = BeanUtils.toBean(reqVO, UserBalanceRecordDO.class);
        balanceRecordDO.setRecordTime(LocalDateTime.now())
                .setPreBalance(preBalance)
                .setPostBalance(postBalance);

        userBalanceRecordMapper.insert(balanceRecordDO);
    }

    @Override
    public void deleteUserBalanceRecord(Long id) {
        // 校验存在
        validateUserBalanceRecordExists(id);
        // 删除
        userBalanceRecordMapper.deleteById(id);
    }

    @Override
    public void deleteUserBalanceRecordListByIds(List<Long> ids) {
        // 删除
        userBalanceRecordMapper.deleteByIds(ids);
    }


    private void validateUserBalanceRecordExists(Long id) {
        if (userBalanceRecordMapper.selectById(id) == null) {
            throw exception(USER_BALANCE_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public UserBalanceRecordDO getUserBalanceRecord(Long id) {
        return userBalanceRecordMapper.selectById(id);
    }

    @Override
    public PageResult<UserBalanceRecordRespVO> getUserBalanceRecordPage(UserBalanceRecordPageReqVO pageReqVO) {
        return userBalanceRecordMapper.selectPage(pageReqVO);
    }
}